package com.education.service.ucenter.controller.web;

import com.education.dto.CourseDto;
import com.education.dto.MemberDto;
import com.education.exception.OnlineEducationException;
import com.education.helper.JwtHelper;
import com.education.helper.JwtInfo;
import com.education.result.R;
import com.education.result.ResultCodeEnum;
import com.education.service.ucenter.entity.form.LoginForm;
import com.education.service.ucenter.entity.form.RegisterForm;
import com.education.service.ucenter.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Lance on 2020/07/04 19:52
 */
@Api(tags = "会员管理")
@RestController
@RequestMapping("/web/ucenter/member")
@Slf4j
public class WebMemberController {

    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterForm registerForm){
        memberService.register(registerForm);
        return R.ok().message("注册成功 !");
    }

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginForm loginForm) {
        String token = memberService.login(loginForm);
        return R.ok().data("token", token);
    }

    /**
     * 获取用户登录信息
     * @param request
     * @return
     */
    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("auth/get-login-info")
    public R getLoginInfo(HttpServletRequest request){
        try{
            JwtInfo jwtInfo = JwtHelper.getJwtInfo(request);
            return R.ok().data("userInfo", jwtInfo);
        }catch (Exception e){
            log.error("解析用户信息失败，" + e.getMessage());
            throw new OnlineEducationException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
    }

    @ApiOperation("根据会员ID查询会员信息")
    @GetMapping("get-member-dto/{memberId}")
    public R getMemberDtoById(@ApiParam(value = "会员ID", required = true) @PathVariable String memberId){
        MemberDto memberDto = memberService.getMemberDtoById(memberId);
        return R.ok().data("memberDto", memberDto);
    }

    @ApiOperation(value = "根据日期统计注册人数")
    @GetMapping(value = "count-register-num/{day}")
    public R countRegisterNum(@ApiParam(name = "day", value = "统计日期")
                              @PathVariable String day){
        Integer num = memberService.countRegisterNum(day);
        return R.ok().data("registerNum", num);
    }
}
